/*
 * @Author: huangyingli
 * @Date: 2023-02-23 17:39:43
 * @LastEditors: huangyingli
 * @LastEditTime: 2023-02-23 20:35:42
 * @Description:
 */
import { useState, useEffect } from 'react';
import style from './ModalManageHandle.module.less';

import Sortable from '../../components/Sortable';
import { ComponentListRequest } from '../../api/conponentManage';
import ComponentCard from '../../components/ComponentCard';

import DynamicComponent from '../../components/DynamicComponent';
import { Button, Input, message } from 'antd';
import { ModalAdd } from '../../api/modalManage';

export default function ModalManageHandle() {
  const [comlists, seComtLists] = useState([]);
  const [modalName, setModalName] = useState('');
  const [messageApi, contextHolder] = message.useMessage();
  const [list, setList] = useState(() =>
    [].map((v) => ({
      key: v,
      children: `Item ${v}`,
    }))
  );

  useEffect(() => {
    ComponentListRequest().then(({ data }) => {
      console.log('组件数据', data);
      seComtLists(data.data);
    });
  }, []);

  function onDrop(ev) {
    ev.preventDefault();
    let data = ev.dataTransfer.getData('application/json');
    console.log('data', data);
    data = JSON.parse(data);
    data.key = Date.now();
    data.children = data.name;
    let l = [...list, data];

    setList(l);
  }

  function onDragOver(ev) {
    ev.preventDefault();
    ev.dataTransfer.dropEffect = 'copy';
  }

  function submit() {
    let data = {
      name: modalName,
      components: list,
    };
    console.log('模板新增数据', data);

    ModalAdd({ data }).then(({ data }) => {
      messageApi.open({
        type: 'success',
        content: '模板保存成功',
      });
    });
  }
  return (
    <>
      {contextHolder}
      <div className={style.wrap}>
        <div className={style.components}>
          <h2>所有组件</h2>

          <div className={style.list}>
            {comlists.map((l, index) => (
              <ComponentCard {...l} key={index}></ComponentCard>
            ))}
          </div>
        </div>
        <div className={style.sortable} onDrop={onDrop} onDragOver={onDragOver}>
          <h2>模板组件</h2>
          <Input
            value={modalName}
            placeholder='请输入模板名称'
            onChange={(e) => setModalName(e.target.value)}
          ></Input>
          <br></br>
          <br></br>
          <Sortable list={list} setList={setList}></Sortable>
        </div>
        <div className={style.preview}>
          {list.map((l) => (
            <DynamicComponent name={l.codeFileName} key={l.key}>
              {l.key}
            </DynamicComponent>
          ))}
        </div>
      </div>
      <div className={style.btnWrap}>
        <Button>取消</Button>
        <Button type='primary' onClick={submit}>
          保存
        </Button>
      </div>
    </>
  );
}
